package mumu.android.lib.view.webview;

import java.util.Date;

import mumu.android.R;
import mumu.android.lib.view.webview.MWebChromeClient.IWebChromeClient;
import mumu.android.lib.view.webview.WebViewLoading.ILoading;

import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WebViewFrame extends LinearLayout {

	private Context mcontext;
	protected static final String TAG = "dd";
	public static final int LOAD_ING = 1;
	public static final int LOAD_OK = 2;
	public static final int LOAD_ERROR_DEFAULT = 3;
	public static final int LOAD_ERROR_TIMEOUT = 4;

	// dom加载完成
	public static final String WEBVIEWBOASTCAST_STRING = "mumu.android.domready";

	public WebViewFrame(Context context, String url) {
		super(context);
		mcontext = context;
		// 本地地址
		url = "file:///android_asset/www/index.html";
//		url = "http://apho.testhk.91.com/Recommend/GoodProduct.aspx?act=0";
//		 url ="http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=index&pv=&z=0&word=%D7%C0%C3%E6&s=0";
		initView(url);
	}

	protected String mUrl;

	private WebViewLoading webViewLoading;
	protected WebViewBase mWebView;
	private MWebChromeClient mWebChromeClient;
	protected TitleBarView mTitleBarView;

	public void initView(String url) {
		// mUrl="http://apho.hk91.test.nd/Public/Ranking.aspx?act=0000";
		this.mUrl = url;
		addView(onCreateView());
	}

	View v;
	PullToRefreshWebView pullToRefreshWebView;

	public View onCreateView() {
		if (v == null) {
			v = ((LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.webview_frame, null);
			pullToRefreshWebView = (PullToRefreshWebView) v.findViewById(R.id.webview);
			View Loading = v.findViewById(R.id.loading);
			webViewLoading = new WebViewLoading(Loading);
			webViewLoading.Loading();
			mWebView = pullToRefreshWebView.getRefreshableView();
			pullToRefreshWebView.setVisibility(View.GONE);
			mTitleBarView = (TitleBarView) v.findViewById(R.id.title_bar);
			mTitleBarView.setUrl(mUrl);
			initWebView();
			// 注册监听广播
			registerbroadcast();
		}
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		v.setLayoutParams(params);
		return v;
	}

	/**
	 * @param viewer
	 */
	protected void initWebView() {
		WebSettings webSettings = mWebView.getSettings();
		// 缓存
		// webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

		webSettings.setAppCacheEnabled(true);
		String dir = mcontext.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
		// 设置应用缓存的路径
		webSettings.setAppCachePath(dir);
		// 设置应用缓存的最大尺寸
		webSettings.setAppCacheMaxSize(1024 * 1024 * 512);
		webSettings.setDomStorageEnabled(true);
		// 根据页面的值缩放
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setBuiltInZoomControls(false); // 设置显示缩放按钮

		webSettings.setSavePassword(false);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setJavaScriptEnabled(true);// 设置支持javascript脚本
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		// webSettings.setSupportZoom(true); //支持缩放
		mWebChromeClient = new MWebChromeClient(new IWebChromeClient() {

			@Override
			public void onProgressChanged(WebView view, int progress) {
				Log.i("dd", " onProgressChanged " + progress + view.isEnabled());

				if (progress == 100) {
					pullToRefreshWebView.onRefreshComplete();
				}

				if (progress >= 100 && view.isEnabled()) {
					Message msg = handler.obtainMessage();// 发送通知，加入线程
					msg.what = LOAD_OK;// 加载完成
					handler.sendMessage(msg);// 通知发送！
				} else {
					webViewLoading.setLoadStr("正在加载" + progress + "%..");
				}
			}
		});
		mWebView.setWebChromeClient(mWebChromeClient);
		mWebView.setWebViewClient(new MWebViewClient(handler));
		mWebView.addJavascriptInterface(new WebViewInterface(mcontext), "AppApi");
		mWebView.loadUrl(mUrl);
	}

	/**
     * 
     */
	public boolean doBack() {
		if (mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		} else {
			return false;
		}
	}

	private Handler handler = new Handler() {
		/**
		 * Subclasses must implement this to receive messages.
		 */
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOAD_ING:
				Log.i("dd", "LOAD_OK");
				webViewLoading.Loading();
				break;
			case LOAD_OK:
				Log.i("dd", "LOAD_OK");
				webViewLoading.hide();
				pullToRefreshWebView.setVisibility(VISIBLE);
				break;
			case LOAD_ERROR_DEFAULT:
			case LOAD_ERROR_TIMEOUT:
				Log.i("dd", "LOAD_ERROR_DEFAULT");
				pullToRefreshWebView.setVisibility(GONE);
				if (msg.what == LOAD_ERROR_TIMEOUT)
					webViewLoading.setErrorTxt("请求超时,点击重试");
				webViewLoading.error(new ILoading() {

					@Override
					public void reload() {
						webViewLoading.Loading();
						pullToRefreshWebView.setVisibility(GONE);
						mWebView.setEnabled(true);
						mWebView.reload();
					}
				});
				break;

			default:
				break;
			}
		}
	};

	/**
	 * 注册监听广播取消loading
	 */
	public void registerbroadcast() {
		/*
		 * http://www.cnblogs.com/trinea/archive/2012/11/09/2763182.html
		 * LocalBroadcastManager只会将广播限定在当前应用程序中
		 */
		LocalBroadcastManager mLocalBroadcastManager = LocalBroadcastManager.getInstance(mcontext);

		IntentFilter filter = new IntentFilter();
		filter.addAction(WEBVIEWBOASTCAST_STRING);

		BroadcastReceiver mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				/*
				 * 第一种loading处理，通过页面加载dom完后，回调接口，发送广播实现loading隐藏
				 * 这种方式可能会出现问题，所有的webview实例都会接受到该条广播，进行更新操作。 需要和唯一标示符进行配合，比较麻烦
				 */
				if (intent.getAction().equals(WEBVIEWBOASTCAST_STRING)) {
					webViewLoading.hide();
					pullToRefreshWebView.setVisibility(View.VISIBLE);
					mWebChromeClient.onProgressChanged(mWebView, 100);

				}
			}
		};
		mLocalBroadcastManager.registerReceiver(mReceiver, filter);
	}

}
